﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;

namespace WindowsFormsApplication1
{

    public partial class selection : Form
    {
        miscellaneousCharges miscellaneousCharges;
        viewPreviousReports viewReports;
        editEmployeeRecordsModule editEmployee;
        tipForm viewTip;
        logInModule parent;
        int privilege;

        public selection(logInModule parent)
        {
            this.parent = parent;
            InitializeComponent();
            showStart();
            updateEndDate();
            viewReports = new viewPreviousReports(this);
            editEmployee = new editEmployeeRecordsModule(this);
            viewTip = new tipForm(this);
            miscellaneousCharges = new miscellaneousCharges(this);
        }

        public void setPrivilege(int privilege)
        {
            this.privilege = privilege;
        }

        public int getPrivilege()
        {
            return privilege;
        }

        private void viewAndAddTipButton_Click(object sender, EventArgs e)
        {
            this.Hide();
            viewTip.Show();
        }

        private void generateReportSheetButton_Click(object sender, EventArgs e)
        {
            EmployeeController empControl = new EmployeeController();
            if (empControl.countEmployees() > 0)
            {
                MiscChargeController miscCharge = new MiscChargeController();
                if (miscCharge.getCurrentDate().Equals(miscCharge.getCurrentEnd()))
                {
                    MessageBox.Show("Unable to generate reports. Last generated reports was today/yesterday", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    updateTipReport();
                    FolderBrowserDialog reportDirectory = new FolderBrowserDialog();
                    reportDirectory.ShowDialog();
                    String path = reportDirectory.SelectedPath;
                    if (!path.Equals(""))
                    {
                        bool success = generateCurrentReport(path);
                        if (success)
                        {
                            LateAbsenceController laControl = new LateAbsenceController();
                            new MiscChargeController().updatePeriod();
                            List<int> list = new EmployeeController().getAllEmployeeCode();
                            foreach (int code in list)
                            {
                                laControl.updateAttendance(code);
                            }
                            bool reset = new EmployeeController().resetAll();
                            if (reset)
                            {
                                miscellaneousCharges.initializeContent();
                                editEmployee.initializeContent();
                                viewReports.initializeContent();
                            }
                            MessageBox.Show("Successfully generated the reports.", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("Unable to generate report", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("There are no active employees in the business.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void viewPreviousReportsButton_Click(object sender, EventArgs e)
        {
            MiscChargeController miscCharge = new MiscChargeController();
            DataTable datatable = miscCharge.getPreviousData();
            if (datatable.Rows.Count > 0)
            {
                this.Hide();
                viewReports.Show();
            }
            else
            {
                MessageBox.Show("There are no previous reports to view.", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public Button getGenerateReportSheet()
        {
            return generateReportSheetButton;
        }

        public Button getViewPreviousReportsButton()
        {
            return viewPreviousReportsButton;
        }

        private void editEmployeeRecords_Click(object sender, EventArgs e)
        {
            this.Hide();
            editEmployee.Show();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            DialogResult result = MessageBox.Show("Are you sure you want to exit the program?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.No)
                e.Cancel = true;
            else
                Environment.Exit(1);
        }

        private void logOut_Click(object sender, EventArgs e)
        {
            this.Hide();
            parent.Show();
        }

        private void tipChargeSetMiscellaneousCharges_Click(object sender, EventArgs e)
        {
            this.Hide();
            miscellaneousCharges.Show();
        }

        private void selection_Load(object sender, EventArgs e)
        {

        }

        public void showStart()
        {
            if (!(new MiscChargeController().isNotEmpty()))
            {
                startUp start = new startUp();
                start.ShowDialog();
            }
        }

        private void updateEndDate()
        {
            MiscChargePeriod miscCharge = new MiscChargePeriod();
            MiscChargeController miscControl = new MiscChargeController();
            DateTime date = DateTime.Now;
            DateTime old = DateTime.Parse(miscControl.getCurrentEnd());
            if (date.CompareTo(old) > 0)
            {
                miscCharge.setEndDate(date.ToString("yyyy-MM-dd"));
                bool success = new MiscChargeController().updateEndDate(miscCharge);
                if (!success)
                {
                    MessageBox.Show("There is an error in updating the date of the period", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void print(Pay pay, String path)
        {
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
            MiscChargeController miscCharge = new MiscChargeController();
            DateTime startDate = DateTime.Parse(miscCharge.getCurrentDate());
            DateTime endDate = DateTime.Parse(miscCharge.getCurrentEnd());
            string title = startDate.ToString("yyyy-MM-dd") + "_" + endDate.ToString("yyyy-MM-dd");
            try
            {
                object oMissing = System.Reflection.Missing.Value;
                Document aDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                WordApp.Visible = false;
                aDoc.Activate();
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                WordApp.Selection.TypeText(pay.firstName + " " + pay.lastName);
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                WordApp.Selection.TypeText("\t\t\t--------------------------------------------------------------------------");
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t+Salary:\t\t\t\t\t\t" + Math.Round(pay.salary,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t+Tip:\t\t\t\t\t\t" + Math.Round(pay.tip,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-Charges:\t\t\t\t\t" + Math.Round(pay.charges,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-Absent:\t\t\t\t\t" + Math.Round(pay.absences,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-Late:\t\t\t\t\t\t" + Math.Round(pay.late,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-Debts:\t\t\t\t\t\t" + Math.Round(pay.debt,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t+Bonuses:\t\t\t\t\t" + Math.Round(pay.bonuses,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-Deductions:\t\t\t\t\t" + Math.Round(pay.deductions,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-SSS:\t\t\t\t\t\t" + Math.Round(pay.SSS,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t-PhilHealth:\t\t\t\t\t" + Math.Round(pay.PhilHealth,2));
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.TypeText("\t\t\t--------------------------------------------------------------------------");
                WordApp.Selection.TypeParagraph();
                WordApp.Selection.Font.Bold = (int)WdConstants.wdToggle;
                WordApp.Selection.TypeText("\t\t\tTotal Pay:\t\t\t\t\t" + Math.Round(pay.TotalPay,2));
                WordApp.Selection.TypeParagraph();
                WordApp.ChangeFileOpenDirectory(path);      
                object saveFilename = pay.lastName + "_" + pay.firstName + title + ".docx";
                aDoc.SaveAs(ref saveFilename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                aDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                WordApp = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Export error: " + ex.Message);
            }
        }

        private bool generateCurrentReport(String path)
        {
            path.Replace("\\", "\\\\");
            EmployeeController employeeControl = new EmployeeController();
            List<string> names = employeeControl.getListNames();
            PayController payControl = new PayController();
            string first;
            string last;
            try
            {
                foreach (string name in names)
                {
                    String[] temp = name.Split(',');
                    last = temp[0];
                    first = temp[1];
                    Pay pay = payControl.getData(first, last);
                    print(pay, path);
                    payControl.addSalaryReport(first, last);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Generate Report Error: "+ex.Message+"\n"+ex.StackTrace);
                return false;
            }
        }

        private void updateTipReport()
        {
            EmployeeController employeeControl = new EmployeeController();
            List<int> employeeCodes = employeeControl.getAllEmployeeCode();
            TipReport tipreport = new TipReport();
            TipReportController tipControl = new TipReportController();
            foreach (int code in employeeCodes)
            {
                tipreport.setEmployeeCode(code);
                tipControl.addTipReport(tipreport);
            }
        }

        public void reInitializeContent()
        {
            viewReports.initializeContent();
        }
    }
}
